<?php

namespace App\Api\Controllers;

use App\Api\Services\JsonService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Api\Models\CmcEmailSubscribel;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Redis;

class SubscribelController extends Controller
{
    /**
     * 添加用户邮箱
     * @param Request $request
     * @return array
     */
    public function getEmail(Request $request)
    {
        try {
            $params = $this->validate($request,[
                    'uid'=>'required|integer',
                    'email'=>'required|email'
                ]);
        } catch (ValidationException $validationException){
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        $params['created_at'] = date('Y-m-d H:i:s',time());

        $countEmailData = CmcEmailSubscribel::countSubEmail($params['uid']);

        if($countEmailData >= 2){
            return JsonService::fail('邮箱绑定上限了','',1003);
        }

        $whereSubEmail = CmcEmailSubscribel::dataSubEmail($params['uid'],$params['email']);

        if($whereSubEmail){
            return JsonService::fail('已经绑定过了','',1003);
        }

        $subEmailRes = CmcEmailSubscribel::addSubEmail($params);

        if($subEmailRes){
            return JsonService::success('成功，请认证邮箱');
        }
        return JsonService::fail('网络出差了，请重试');
    }

    /**
     * 
     * @param Request $request
     * @return array
     */
    public function getEmailCatch(Request $request)
    {
        try {
            $params = $this->validate($request,[
                'uid'=>'required|integer',
                'email'=>'required|email',
                'cache'=>'required|integer'
            ]);
        }catch (ValidationException $validationException){
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $cache = Redis::get($params['email']);

        if($cache != $params['cache']){
            return JsonService::fail('验证码输入错误','',1003);
        }

        $subEmailRes = CmcEmailSubscribel::saveSubEmail($params['uid'],$params['email']);

        if($subEmailRes){
            return JsonService::success('认证成功');
        }
        return JsonService::fail('验证码输入错误，请重试','',1003);
    }
}